package com.mgface.zookeeper.curator;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * 异步处理方法
 * 
 * @author user
 *
 */
public class Async {

	public static void main(String[] args) throws Exception {
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183").sessionTimeoutMs(10_000)
				// .namespace("curator")//指定隔离命名空间
				.retryPolicy(new ExponentialBackoffRetry(100, 3))// baseSleepTimeMs：初始sleep时间
				.build();
		client.start();
		System.out.println("启动完毕...");
		CountDownLatch cdl = new CountDownLatch(2);
		ExecutorService exec = Executors.newFixedThreadPool(2);
		client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground((cli, event) -> {
			System.out.println("event[code:"+event.getResultCode()+",type:"+event.getType()+"]");
			cdl.countDown();
		}, exec).forPath("/async", "init".getBytes());
		client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground((cli, event) -> {
			System.out.println("event[code:"+event.getResultCode()+",type:"+event.getType()+"]");
			cdl.countDown();
		}, exec).forPath("/async", "init".getBytes());
		cdl.await();
		exec.shutdown();
	}

}
